import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card,Row, Col, Divider,message} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule,updateFunctionRule } from '../service';
import styles from '../style.less';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureLogo, setPictureLogo] = useState<any[]>([]);
  const [uploadLogoChanged, setUploadLogoChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      
      console.log("submit fields ", fieldsValue)
      var submitValue = [
          {
            //请求当前一组配置参数，tag=wallets
            "alias_key": 'wallets',
            "item_type":'system',
            "dict_item_arr": [
              {
                "alias_key": "wallet_status",
                "item_value": fieldsValue.wallet_status,
                'item_type':"radio",
              },
              {
                "alias_key": "wallet_currency_code",
                "item_value": fieldsValue.wallet_status ? fieldsValue.wallet_currency_code : parseData('wallet_status',dataFormValues),
                'item_type':"select",
              },
              {
                "alias_key": "wallet_withdraw_close",
                "item_value": fieldsValue.wallet_status ? fieldsValue.wallet_withdraw_close : parseData('wallet_withdraw_close',dataFormValues),
                'item_type':"radio",
              },
              {
                "alias_key": "wallet_withdraw_review",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_review : parseData('wallet_withdraw_review',dataFormValues),
                'item_type':"radio",
              },
              {
                "alias_key": "wallet_withdraw_verify",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_verify : parseData('wallet_withdraw_verify',dataFormValues),
                'item_type':"radio",
              },
              {
                "alias_key": "wallet_withdraw_interval_time",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_interval_time : parseData('wallet_withdraw_interval_time',dataFormValues),
                'item_type':"number",
              },
              {
                "alias_key": "wallet_withdraw_rate",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_rate : parseData('wallet_withdraw_rate',dataFormValues),
                'item_type':"text",
              },
              {
                "alias_key": "wallet_withdraw_min_sum",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_min_sum : parseData('wallet_withdraw_min_sum',dataFormValues),
                'item_type':"number",
              },
              {
                "alias_key": "wallet_withdraw_max_sum",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_max_sum : parseData('wallet_withdraw_max_sum',dataFormValues),
                'item_type':"number",
              },
              {
                "alias_key": "wallet_withdraw_sum_limit",
                "item_value": (fieldsValue.wallet_status && fieldsValue.wallet_withdraw_close) ? fieldsValue.wallet_withdraw_sum_limit : parseData('wallet_withdraw_sum_limit',dataFormValues),
                'item_type':"number",
              },
            ]
          },
      ]
      // 如果更新成功之后，重置表单
      updateFunctionRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
        console.log('handleSubmit then success is ', JSON.stringify(submitValue))
        if(res.code == 0){
          message.success('保存成功')
          // form.resetFields()
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置Logo上传文件值
    const setLogoUploadFile = (fileList:any) => {
      setUploadLogoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureLogo(fileArr)
        setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureLogo([])
      }
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      return name
    }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.site_icon)
  const defaultLogoPicture = DataHelper.buildFileByUrl(dataFormValues.site_logo)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadLogoButton = DataHelper.showUploadBtn(isUpdate, pictureLogo, defaultLogoPicture, uploadLogoChanged)
  

  // 弹出框
  // @ts-ignore
  return <Card>
      <Row>
        <Col span={14}>
          <FormItem label={formatMessage({id: 'wallet function'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
              {form.getFieldDecorator('wallet_status', {
                initialValue: parseData('wallet_status',dataFormValues) || false,
              })(<Radio.Group buttonStyle="solid" >
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>启用</Radio>
            </Radio.Group>)}
          </FormItem>
        </Col>
        <Col offset={1} span={7}>
          <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>是否启用钱包功能</span>
        </Col>
      </Row>

      {
        form.getFieldValue('wallet_status') == true && 
        <>
        <Row>
          <Col span={14}>
          <FormItem label={formatMessage({id: 'Wallet currency code'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
          {form.getFieldDecorator('wallet_currency_code', {
            initialValue: parseData('wallet_currency_code',dataFormValues),
            //  rules: [{ required: true, message: '请选择！',}],
          })(<Select size={'default'} style={{ width: '100%' }}>
            {common.walletCurrencyCodeOption  && TsxHelper.buildSelectOption(common.walletCurrencyCodeOption )}
          </Select>)}
        </FormItem>
          </Col>
          <Col offset={1} span={7}>
            {/* <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>ISO 4217 标准的货币代码，例如人民币是 CNY，美元是 USD</span> */}
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Withdrawal function'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_close', {
                  initialValue: parseData('wallet_withdraw_close',dataFormValues) || false,
                })(<Radio.Group buttonStyle="solid" >
                <Radio value={false}>关闭</Radio>
                <Radio value={true}>启用</Radio>
              </Radio.Group>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>钱包余额是否可以提现</span>
          </Col>
        </Row>
        </>
      }
      {
        form.getFieldValue('wallet_withdraw_close') == true && 
        <>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Withdrawal audit'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_review', {
                  initialValue: parseData('wallet_withdraw_review',dataFormValues) || false,
                })(<Radio.Group buttonStyle="solid" >
                <Radio value={false}>不审核</Radio>
                <Radio value={true}>需审核</Radio>
              </Radio.Group>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>提现相关配置需插件支持，详细请咨询插件开发者。</span>
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Withdrawal whether to verify the real name information'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_verify', {
                  initialValue: parseData('wallet_withdraw_verify',dataFormValues) || false,
                })(<Radio.Group buttonStyle="solid" >
                <Radio value={false}>不验证</Radio>
                <Radio value={true}>启用验证</Radio>
              </Radio.Group>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            {/* <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>启用后，提现将验证真实姓名和身份证号</span> */}
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Time between withdrawals'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_interval_time', {
                  initialValue: parseData('wallet_withdraw_interval_time',dataFormValues),
                  rules:[{ pattern: /^[0-9]*$/, message: '请输入合理的间隔时间' }]
                })(<Input style={{width: '100%'}}  addonAfter="分钟"/>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            {/* <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>0 或不填则不限制</span> */}
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Withdrawal rate'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_rate', {
                  initialValue: parseData('wallet_withdraw_rate',dataFormValues),
                  rules:[{ pattern: /^[0-9]*$/, message: '请输入合理的间隔时间' }]
                })(<Input style={{width: '100%'}}  addonAfter="%"/>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            {/* <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>百分比，6 代表 6%</span> */}
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'minimum amount withdrawn at one time'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_min_sum', {
                  initialValue: parseData('wallet_withdraw_min_sum',dataFormValues),
                  rules:[{ pattern: /^[0-9]*$/, message: '请输入合理的金额' }]
                })(<Input style={{width: '100%'}}  addonAfter="元"/>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}></span>
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Maximum amount withdrawn at one time'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_max_sum', {
                  initialValue: parseData('wallet_withdraw_max_sum',dataFormValues),
                  rules:[{ pattern: /^[0-9]*$/, message: '请输入合理的金额' }]
                })(<Input style={{width: '100%'}}  addonAfter="元"/>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}></span>
          </Col>
        </Row>
        <Row>
          <Col span={14}>
            <FormItem label={formatMessage({id: 'Maximum amount of total daily withdrawal'})} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} style={{marginBottom: 15}}>
                {form.getFieldDecorator('wallet_withdraw_sum_limit', {
                  initialValue: parseData('wallet_withdraw_sum_limit',dataFormValues),
                  rules:[{ pattern: /^[0-9]*$/, message: '请输入合理的金额' }]
                })(<Input style={{width: '100%'}}  addonAfter="元"/>)}
            </FormItem>
          </Col>
          <Col offset={1} span={7}>
            {/* <span style={{height:32,lineHeight:'32px',display:'block',marginTop:2}}>所有用户单日提现的上限总金额</span> */}
          </Col>
        </Row>
        </>
      }
    

    

    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okHandle()}}>保存</Button>
        {/* <Button type="default" style={{marginLeft:30}}>发信测试</Button> */}
      </div>
    </Col>
  </Card>;
};

export default Form.create<DataFormProps>()(DataForm);
